<?php

/**
 * LinkTeacherProgram filter form.
 *
 * @package    sf_sandbox
 * @subpackage filter
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormFilterTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class LinkTeacherProgramFormFilter extends BaseLinkTeacherProgramFormFilter {

    public function configure() {
        $choices = array('' => '');
        foreach (LinkTeacherProgramTable::$assign_status_arr as $val => $txt) {
            $choices[$val] = $txt;
        }
        $this->widgetSchema['assign_status'] = new sfWidgetFormChoice(array('choices' => $choices));
        $this->validatorSchema['assign_status'] = new sfValidatorChoice(array('choices' => array_keys(LinkTeacherProgramTable::$assign_status_arr), 'required' => false));

        $this->widgetSchema['program_code'] = new sfWidgetFormFilterInput(array('with_empty' => false));
        $this->validatorSchema['program_code'] = new sfValidatorPass(array('required' => false));

        $this->widgetSchema['program_id'] = new sfWidgetFormDoctrineChoice(array('model' => 'Program', 'add_empty' => true, 'order_by' => array('name', 'asc')));
        $this->validatorSchema['program_id'] = new sfValidatorDoctrineChoice(array('model' => 'Program', 'required' => false));

        $this->widgetSchema['school_id'] = new sfWidgetFormDoctrineChoice(array('model' => 'School', 'add_empty' => true, 'order_by' => array('name', 'asc')));
        $this->validatorSchema['school_id'] = new sfValidatorDoctrineChoice(array('model' => 'School', 'required' => false));
    }

    public function buildQuery(array $values) {
        $q = parent::buildQuery($values);

        if (isset($values['school_id']) && !empty($values['school_id'])) {
            $q->innerJoin('r.Teacher t')
                    ->addWhere('t.school_intg_id = ?', $values['school_id']);
        }
        if (isset($values['program_code']['text']) && !empty($values['program_code']['text'])) {
            $q->innerJoin('r.Program p')
                    ->addWhere('p.program_code = ?', $values['program_code']['text']);
        }



        // --------------

            $user = sfContext::getInstance()->getUser();

            if ($user->hasAttribute('kts_global_program_filter') && is_array($data = $user->getAttribute('kts_global_program_filter'))) {
                $semister_map = array(1 => 'first', 2 => 'second');
                $q->innerJoin('r.Program p');
                $q->addWhere('p.semester = ?', $semister_map[$data['semester']]);
                $q->addWhere('p.academic_year_id = ?', $data['year']);
            }

        // --------------


        return $q;
    }

    public function getFields() {
        return array(
            'program_id' => 'ForeignKey',
            'teacher_id' => 'ForeignKey',
            'assign_status' => 'Enum',
            'created_at' => 'Date',
        );
    }

}
